package com.whfc.ms.api.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.whfc.base.entity.AppMessage;
import com.whfc.base.service.MessageService;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.*;
import com.whfc.common.result.PageData;
import com.whfc.common.util.NumberParser;
import com.whfc.common.util.PageUtil;
import com.whfc.emp.dto.AppAttachDTO;
import com.whfc.emp.dto.AppEmpDTO;
import com.whfc.emp.dto.AppWorkTypeDTO;
import com.whfc.emp.entity.*;
import com.whfc.emp.entity.AppWorkPlan;
import com.whfc.emp.service.*;
import com.whfc.entity.dto.Apply.rep.*;
import com.whfc.entity.dto.Apply.req.*;
import com.whfc.entity.dto.msg.AppMsgToUserDTO;
import com.whfc.entity.dto.msg.PushMsgDTO;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.service.SysDeptService;
import com.whfc.fuum.service.SysUserService;
import com.whfc.mach.service.AppMachService;
import com.whfc.ms.api.sys.dto.ApprovalRecordDTO;
import com.whfc.ms.api.sys.dto.EntryApplicationDTO;
import com.whfc.ms.api.sys.dto.EntryApplicationDetailRep;
import com.whfc.ms.api.sys.service.SysApplyService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysApplyServiceImpl implements SysApplyService {

    @DubboReference(interfaceClass = AppEntryApplicationService.class, version = "1.0.0", timeout = 30000)
    private AppEntryApplicationService appEntryApplicationService;

    @DubboReference(interfaceClass = AppEmpService.class, version = "1.0.0", timeout = 30000)
    private AppEmpService appEmpService;

    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0", timeout = 30000)
    private SysDeptService sysDeptService;

    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0", timeout = 30000)
    private SysUserService sysUserService;

    @DubboReference(interfaceClass = MessageService.class, version = "1.0.0", timeout = 30000)
    private MessageService messageService;

    @DubboReference(interfaceClass = ApprovalRecordService.class, version = "1.0.0", timeout = 50000)
    private ApprovalRecordService approvalRecordService;

    @DubboReference(interfaceClass = AppWorkPlanService.class, version = "1.0.0", timeout = 30000)
    private AppWorkPlanService appWorkPlanService;

    @DubboReference(interfaceClass = AppContractService.class, version = "1.0.0", timeout = 30000)
    private AppContractService appContractService;

    @DubboReference(interfaceClass = AppEmpHealthReportService.class, version = "1.0.0", timeout = 30000)
    private AppEmpHealthReportService appEmpHealthReportService;

    @DubboReference(interfaceClass = AppEmpWorkService.class, version = "1.0.0", timeout = 30000)
    private AppEmpWorkService appEmpWorkService;

    @DubboReference(interfaceClass = PlanCategoryService.class, version = "1.0.0", timeout = 30000)
    private PlanCategoryService planCategoryService;

    @DubboReference(interfaceClass = AppMachService.class, version = "1.0.0", timeout = 30000)
    private AppMachService appMachService;


    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public PageData<EntryApplicationListRep> list(SysUser user,AppEntryApplicationReq request) {
        return appEntryApplicationService.getAppEntryList(user,request);
    }

    @Override
    public String saveApplyPersonnel(SysUser user, AppEntryApplicationDTO req) {

        // 人员入场
        AppEntryApplicationDTO AppEntryApplicationDTO = appEntryApplicationService.saveApply(user.getId(),req);
        if(AppEntryApplicationDTO.getId() == null){
            return "提交失败";
        }

        // 查询项目下的个个机构管理人员
        List<UserDeptDTO> userDeptDTOS = sysDeptService.queryMessage(req.getDeptId());
        List<AppMessage> appMessages = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userDeptDTOS)) {
            for (UserDeptDTO userDept : userDeptDTOS) {
                if(Objects.equals(userDept.getUserType(), SysUserUserType.OWNER.getValue())
                        || Objects.equals(userDept.getUserType(),SysUserUserType.SUPERVISOR.getValue())){
                    // 存储审核信息
                    ApprovalRecord approvalRecord = new ApprovalRecord();
                    approvalRecord.setApplicationId(AppEntryApplicationDTO.getId());
                    approvalRecord.setApproverType(userDept.getUserType());
                    approvalRecord.setApproverId(userDept.getUserId());
                    approvalRecord.setReviewType(ReviewType.ENTRANCE_REVIEW.getValue());
                    approvalRecord.setApprovalResult(ApprovalResult.PENDING.getValue());
                    approvalRecordService.insertApprovalRecord(approvalRecord);

                    // 人员入场申给审批人发送消息提醒
                    buildMessage(userDept, appMessages);
                }
            }
        }
//        messageService.addAppMessage(appMessages);
        return "提交成功";
    }

    private void buildMessage(UserDeptDTO userDept, List<AppMessage> appMessages) {
        if (userDept == null || userDept.getUserType().equals(SysUserUserType.COMMON.getValue())) return;
        
        // 创建接收人列表
        List<AppMsgToUserDTO> toUserList = new ArrayList<>();
        AppMsgToUserDTO userDTO = new AppMsgToUserDTO();
        userDTO.setUserId(userDept.getUserId());
        userDTO.setUsername(userDept.getUserName());
        userDTO.setPhone(userDept.getPhone());
        userDTO.setDeptId(userDept.getDeptId());
//        userDTO.setDeptName(userDept.getDeptName());
        toUserList.add(userDTO);
        
        // 创建推送消息DTO
        PushMsgDTO pushMsgDTO = new PushMsgDTO();
        pushMsgDTO.setTitle("人员入场审批");
        pushMsgDTO.setContent("您有需要审批的单子请及时处理");
        pushMsgDTO.setDeptId(userDept.getDeptId());
        pushMsgDTO.setTime(new Date());
        pushMsgDTO.setModuleType(10);
        pushMsgDTO.setMsgObjectId("1");
        pushMsgDTO.setToUserList(toUserList);
        
        // 设置消息渠道：PC(3)和APP(1)
        List<Integer> msgChannelList = new ArrayList<>();
        msgChannelList.add(3); // PC
        msgChannelList.add(1); // APP
        pushMsgDTO.setMsgChannelList(msgChannelList);
        
        // 通过MQ发送消息
        amqpTemplate.convertAndSend(QueueConst.PUSH_MSG_EXCHANGE, "", JSON.toJSONString(pushMsgDTO));
        
        // 保留原有的AppMessage构建逻辑，用于兼容性
//        AppMessage appMessage = new AppMessage();
//        appMessage.setContent("您有需要审批的单子请及时处理");
//        appMessage.setDeptId(userDept.getDeptId());
//        appMessage.setTitle("人员入场审批");
//        appMessage.setToUserId(userDept.getUserId());
//        appMessage.setToUserName(userDept.getUserName());
//        appMessage.setToUserPhone(userDept.getPhone());
//        appMessage.setMsgType(AppWarnModuleType.MACH.value());
//        appMessage.setMsgChannel(AppWarnMsgChannel.WXMP.value());
//        appMessage.setMsgObjectId("1");
//        appMessage.setModuleType(10);
//        appMessage.setTime(new Date());
//        appMessage.setState(0);
//        appMessage.setDelFlag(0);
//        appMessage.setCreateTime(new Date());
//        appMessage.setUpdateTime(new Date());
//        appMessages.add(appMessage);
//
//        AppMessage msMessage = new AppMessage();
//        msMessage.setContent("您有需要审批的单子请及时处理");
//        msMessage.setDeptId(userDept.getDeptId());
//        msMessage.setTitle("人员入场审批");
//        msMessage.setToUserId(userDept.getUserId());
//        msMessage.setToUserName(userDept.getUserName());
//        msMessage.setToUserPhone(userDept.getPhone());
//        msMessage.setMsgType(AppWarnModuleType.MACH.value());
//        msMessage.setMsgChannel(AppWarnMsgChannel.MS.value());
//        msMessage.setMsgObjectId("1");
//        msMessage.setModuleType(10);
//        msMessage.setTime(new Date());
//        msMessage.setState(0);
//        msMessage.setDelFlag(0);
//        msMessage.setCreateTime(new Date());
//        msMessage.setUpdateTime(new Date());
//        appMessages.add(msMessage);
    }


    @Override
    public List<SafetyTrainingExamReq> queryPersonnel(QueryPersonnelReq req) {
        // 获取非系统人员信息
        List<AppEmpDTO> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(req.getEmpNames())){
            for (String empName : req.getEmpNames()) {
                list.addAll(appEmpService.list(req.getDeptId(), empName));
                if (CollectionUtils.isEmpty(list)) {
                    return null;
                }
            }

        }
        List<SafetyTrainingExamReq> safetyTrainingExamReqs = new ArrayList<>();
        List<QueryEmpSysIdDto> appEmpIds = null;
        if(CollectionUtils.isEmpty(list)){
            appEmpIds = sysUserService.getAppEmps(null,req.getDeptId());
        }else {
            for(AppEmpDTO appEmpDTO : list){
                appEmpIds = sysUserService.getAppEmps(appEmpDTO.getEmpId(),req.getDeptId());
            }

        }

        for (QueryEmpSysIdDto queryEmpSysId : appEmpIds) {
            AppEmpDTO empInfo = appEmpService.getEmpInfo(queryEmpSysId.getAppEmpId());
            empInfo.setEmpId(queryEmpSysId.getSysUserId());
            SafetyTrainingExamReq safetyTrainingExamReq = convertToExamReq(empInfo);
            safetyTrainingExamReqs.add(safetyTrainingExamReq);
        }
        return safetyTrainingExamReqs;
    }

    private List<Map<String, String>> convertAttachList(List<AppAttachDTO> attachList) {
        // 空集合直接返回空列表，避免后续流处理空指针
        if (CollectionUtils.isEmpty(attachList)) {
            return Collections.emptyList();
        }

        return attachList.stream()
                .filter(Objects::nonNull)
                .filter(dto ->
                        // 统一过滤条件：name和url非空且非空白
                        dto.getName() != null && !dto.getName().trim().isEmpty() &&
                                dto.getUrl() != null && !dto.getUrl().trim().isEmpty()
                )
                .map(dto -> {
                    Map<String, String> map = new HashMap<>(2);
                    map.put("name", dto.getName().trim());
                    map.put("url", dto.getUrl().trim());
                    return map;
                })
                .collect(Collectors.toList());
    }

    private SafetyTrainingExamReq convertToExamReq(AppEmpDTO empDTO) {
        SafetyTrainingExamReq req = new SafetyTrainingExamReq();

        // 基础信息映射
        req.setEmp_id(empDTO.getEmpId());
        req.setName(empDTO.getEmpName());
        req.setGender(convertGender(empDTO.getGender()));
        req.setCompany(empDTO.getCorpName());
        req.setPosition(empDTO.getWorkTypeName());
        req.setAddress(empDTO.getAddress());
        req.setHardwareNumber(empDTO.getSn());
        req.setExamStatus("未考试");
        req.setContractEndDate(empDTO.getContractEndDate());
        req.setHealthEndDate(empDTO.getHealthEndDate());
        req.setJourneyEndDate(empDTO.getJourneyEndDate());
        req.setCredEndDate(empDTO.getCredEndDate());
        req.setGroupId(empDTO.getGroupId());
        req.setGroupName(empDTO.getGroupName());
        req.setCorpId(empDTO.getCorpId());
        req.setCorpName(empDTO.getCorpName());

        // 合同信息
        List<AppAttachDTO> contractDTOs = appContractService.selectByEmpIdUrl(empDTO.getEmpId());
        req.setContractFileName(convertAttachList(contractDTOs));

        // 资质证书信息
        List<AppAttachDTO> certDTOs = appEmpService.selectByEmpIdUrl(empDTO.getEmpId());
        req.setQualificationCertificateNmae(convertAttachList(certDTOs));

        // 体检报告（类型1）
        List<AppAttachDTO> healthReportDTOs = appEmpHealthReportService.selectByEmpIdImg(empDTO.getEmpId(), "1");
        req.setMedicalReportNmae(convertAttachList(healthReportDTOs));

        // 社保证明（类型2）
        List<AppAttachDTO> insuranceDTOs = appEmpHealthReportService.selectByEmpIdImg(empDTO.getEmpId(), "2");
        req.setSocialSecurityProofNmae(convertAttachList(insuranceDTOs));

        return req;
    }

    /**
     * 性别转换工具方法
     */
    private String convertGender(Integer gender) {
        return gender == null ? "未知" :
                gender == 1 ? "男" :
                        gender == 2 ? "女" : "未知";
    }

    @Override
    public List<InstitutionRep> queryInstitution(SysUser user,Integer deptId) {
        if (user == null) {
            return Arrays.asList();
        }
        return sysDeptService.getUnit(deptId);
    }

    @Override
    public PageData<EntryApplicationDTO> entryReview(SysUser user, AppEntryApplicationReq req) {
        // 查询当前登录账号的申请记录
        String integers = sysDeptService.selectDeptIdById(user.getId());
        List<Integer> pidList = NumberParser.parseCommaSeparatedNumbers(integers);
        PageData<AppEntryApplication> applications = appEntryApplicationService
                .selectByTimeAndStatus(pidList, req.getUserId(), req.getEntryTimeBegin(), req.getEntryTimeEnd(),
                        req.getLeaveTimeBegin(), req.getLeaveTimeEnd(), req.getAuditStatus(), req.getPageNum(), req.getPageSize());
        // 打印分页信息用于调试
        log.info("entryReview分页参数 - PageNum: {}, PageSize: {}", req.getPageNum(), req.getPageSize());
        log.info("查询结果 - 总记录数: {}, 当前页记录数: {}", applications.getTotal(), applications.getList().size());

        List<EntryApplicationDTO> responses = new ArrayList<>();
        for (AppEntryApplication application : applications.getList()) {
            EntryApplicationDTO ret = getByEntryApplicationId(application.getId(), ReviewType.ENTRANCE_REVIEW.getValue(), user.getId());
            if (ret != null) {
                responses.add(ret);
            }
        }

        // 创建返回的分页结果
        PageInfo<EntryApplicationDTO> resultPage = new PageInfo<>(responses);
        resultPage.setTotal(applications.getTotal());
        resultPage.setPageNum(applications.getPageNum());
        resultPage.setPageSize(applications.getPageSize());
        resultPage.setPages(applications.getPages());

        log.info("entryReview分页结果 - 总记录数: {}, 总页数: {}, 当前页: {}",
                resultPage.getTotal(), resultPage.getPages(), resultPage.getPageNum());

        return PageUtil.pageData(resultPage);
    }

    /**
     * 根据申请id查询申请审核记录
     *
     * @param
     * @return
     */
    private EntryApplicationDTO getByEntryApplicationId(Integer entryApplicationId, Integer reviewType,
                                                        Integer currentUserId) {
        EntryApplicationDTO response = new EntryApplicationDTO();
        response.setEntryApplicationId(entryApplicationId);
        response.setFlag(false);
        // 1、根据申请记录id查询申请记录
        AppEntryApplication appEntryApplication = appEntryApplicationService.selectByPrimaryKey(entryApplicationId);
        if (appEntryApplication == null) {
            return null;
        }
        response.setTeamLeader(appEmpService.getEmpInfo(appEntryApplication.getTeamLeaderId()));
        String[] entryPersonIds = appEntryApplication.getEntryPersonId().split("/");
        List<SysUser> enteryPersonList = new ArrayList<>();
        for (String entryPersonId : entryPersonIds) {
            enteryPersonList.add(sysUserService.getUserById(Integer.parseInt(entryPersonId)));
        }
        response.setEntryPersons(enteryPersonList);
        SysUser applicant = null;// 申请人
        // 2、根据申请人id查询申请人信息
        if (!StringUtils.isEmpty(appEntryApplication.getCreateUser())) {
            applicant = sysUserService.getUserById(Integer.parseInt(appEntryApplication.getCreateUser()));
        }
        response.setEntryApply(appEntryApplication);
        Map<Integer, Boolean> needApproval = new HashMap<>();
        // 2、根据申请记录id和审核类型查询审核记录
        List<ApprovalRecordDTO> approvalRecords = new ArrayList<>();
        List<ApprovalRecord> approvalRecordList = approvalRecordService.selectRecordByApplyIdAndAuditType(entryApplicationId,
                reviewType);
        for (ApprovalRecord approvalRecord : approvalRecordList) {
            ApprovalRecordDTO recordDTO = new ApprovalRecordDTO();
            BeanUtils.copyProperties(approvalRecord, recordDTO);
            recordDTO.setApplicantUser(applicant);
            // 4、根据审核人id查询审核人信息
            SysUser approvalUser = sysUserService.getUserById(approvalRecord.getApproverId());
            if (approvalUser == null || approvalUser.getUserType() == null)
                continue;
            recordDTO.setApprovalUser(approvalUser);
            approvalRecords.add(recordDTO);
            if (approvalRecord.getApprovalResult().equals(ApprovalResult.PENDING.getValue())
                    && (!needApproval.containsKey(approvalUser.getUserType())
                    || needApproval.get(approvalUser.getUserType()) != false)) {
                needApproval.put(approvalUser.getUserType(), true);
            } else if (approvalRecord.getApprovalResult().equals(ApprovalResult.APPROVE.getValue())) {
                needApproval.put(approvalUser.getUserType(), false);
            }
        }
        // 按审核人类型倒序排列
        approvalRecords.sort((o1, o2) -> o2.getApprovalUser().getUserType() - o1.getApprovalUser().getUserType());
        // 简易版工作流 计算当前审核节点
        Integer approvalStep = SysUserUserType.SUPERVISOR.getValue();
        needApproval = needApproval.entrySet().stream()
                .sorted(Map.Entry.<Integer, Boolean>comparingByKey().reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1, // 合并函数，如果有重复key
                        LinkedHashMap::new // 保持排序顺序
                )); // 按照key倒序排列
        Optional<Integer> firstFalseKey = needApproval.entrySet()
                .stream()
                .filter(Map.Entry::getValue) // value == true
                .map(Map.Entry::getKey)
                .findFirst();
        if (firstFalseKey.isPresent()) {
            approvalStep = firstFalseKey.get();
        }
        // 设置当前审核节点审核人员审核权限
        for (ApprovalRecordDTO dto : approvalRecords) {
            if (dto.getApprovalResult().equals(ApprovalResult.PENDING.getValue())
                    && dto.getApprovalUser().getUserType().equals(approvalStep)) {
                dto.setFlag(true);
                if (dto.getApprovalUser().getId().equals(currentUserId)) {
                    response.setFlag(true);
                }
            } else {
                dto.setFlag(false);
            }
        }
        response.setApprovalRecords(approvalRecords);
        return response;
    }

    @Override
    public String applyEntryReview(SysUser user, Integer approvalResult, Integer id) {
        // 获取当前审核记录
        ApprovalRecord currentRecord = approvalRecordService.getApprovalRecordById(id);
        if (approvalResult.equals(ApprovalResult.APPROVE.getValue())) {
            // 当前节点审批通过
            currentRecord.setApprovalResult(ApprovalResult.APPROVE.getValue());
            currentRecord.setApprovalTime(new Date());
            approvalRecordService.updateApprovalRecord(currentRecord);
            // 查看是否还有下一个节点
            Integer nextNode = getNextNode(currentRecord.getApproverType());
            // 设置当前申请记录状态
            AppEntryApplication entryApplication = appEntryApplicationService
                    .selectByPrimaryKey(currentRecord.getApplicationId());
            if (nextNode == null) {
                // 没有下一个审核节点，申请审核通过
                entryApplication.setApprovalStatus(ApprovalResult.APPROVE.getValue());
                appEntryApplicationService.updateApprovalResult(entryApplication);
            } else if (entryApplication.getApprovalStatus().equals(ApprovalResult.PENDING.getValue())) {
                entryApplication.setApprovalStatus(ApprovalResult.APPROVING.getValue());
                appEntryApplicationService.updateApprovalResult(entryApplication);
            }
            // 设置同类型其余审核记录：无需审核
            List<ApprovalRecord> approvalRecordList = approvalRecordService.selectRecordByApplyIdAndAuditType(currentRecord.getApplicationId(), ReviewType.PLAN_REVIEW.getValue());
            for (ApprovalRecord record: approvalRecordList){
                if (record.getApproverType().equals(currentRecord.getApproverType())){
                    if (!currentRecord.getId().equals(record.getId())) {
                        record.setApprovalResult(ApprovalResult.COMPLETED.getValue());
                        record.setApprovalTime(new Date());
                        approvalRecordService.updateApprovalRecord(record);
                    }
                }
            }
        } else if(approvalResult.equals(ApprovalResult.REJECT.getValue())){
            // 当前审批节点
            currentRecord.setApprovalResult(ApprovalResult.REJECT.getValue());
            currentRecord.setApprovalTime(new Date());
            approvalRecordService.updateApprovalRecord(currentRecord);
            // 申请记录
            AppEntryApplication entryApplication = appEntryApplicationService.selectByPrimaryKey(currentRecord.getApplicationId());
            entryApplication.setApprovalStatus(ApprovalResult.REJECT.getValue());
            appEntryApplicationService.updateApprovalResult(entryApplication);
        }
        return "审核成功!";
    }

    @Override
    public String uplodFile(MultipartFile file) {
        // 获取项目根目录路径
        String projectRootPath = System.getProperty("user.dir");
        // 创建uploads子目录（避免根目录文件混乱）
        String uploadDir = projectRootPath + File.separator + "uploads";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs(); // 递归创建目录
        }

        // 生成唯一文件名（避免重名覆盖）
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        // 构建完整文件路径
        String filePath = uploadDir + File.separator + uniqueFileName;
        File destFile = new File(filePath);

        // 保存文件到磁盘
        try {
            file.transferTo(destFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return filePath;
    }

    @Override
    public List<StaffInfoRep> querycheckInList(QuerycheckInListReq req) {

        return Collections.emptyList();
    }



    @Override
    public List<AppWorkTypeDTO> queryCategory(Integer depyId) {
        return appEmpWorkService.workTypeList(depyId);
    }

    @Override
    public EntryApplicationDetailRep queryEntryDetails(Integer id) {
        // 入厂申请基本信息
        EntryApplicationDetailRep rep = new EntryApplicationDetailRep();
        // 人员基本信息
        List<EntryPersonInfo> entryList = new ArrayList<>();
        //获取当前入场申请
        AppEntryApplication entry = appEntryApplicationService.selectByPrimaryKey(id);

        // 获取入场人员
        List<String> person = null;
        if(entry.getEntryPersonId().contains("/")){
            person = Arrays.asList(entry.getEntryPersonId().split("/"));
        }else {
            person =  Arrays.asList(entry.getEntryPersonId());
        }
        List<String> names = new ArrayList<>();
        List<QueryEmpSysIdDto> appEmpIds = sysUserService.getAppEmpEmpNamesIdList(person);
        for (QueryEmpSysIdDto emp : appEmpIds) {
            // 人员信息
            EntryPersonInfo personInfo = new  EntryPersonInfo();
            AppEmpDTO info = appEmpService.getEmpInfo(emp.getAppEmpId());
            SafetyTrainingExamReq safetyTrainingExamReq = convertToExamReq(info);
            personInfo.setName(safetyTrainingExamReq.getName());
            personInfo.setGender(safetyTrainingExamReq.getGender());
            personInfo.setCompany(safetyTrainingExamReq.getCompany());
            personInfo.setPosition(safetyTrainingExamReq.getPosition());
            personInfo.setHardwareNo(safetyTrainingExamReq.getHardwareNumber());
            personInfo.setExamStatus(safetyTrainingExamReq.getExamStatus());
            PlanCategory planCategory = planCategoryService.getPlanCategory(id, emp.getSysUserId());
            if(planCategory != null){
                personInfo.setFactoryPosition(planCategory.getCategoryName());
            }else {
                personInfo.setFactoryPosition("暂无待配置");
            }
            entryList.add(personInfo);
            // 入厂申请基本信息-人员名称
            names.add(info.getEmpName());
        }
        rep.setEntryPersonNameList(names);
        rep.setEntryPersonInfoList(entryList);

        // 获取组长
        rep.setTeamLeader(appEmpService.getEmpInfo(entry.getTeamLeaderId()));
        rep.setApprovalRecord(approvalRecordService.selectRecordByApplyIdAndAuditType(id, ReviewType.ENTRANCE_REVIEW.getValue()));
        // 入场时间
        rep.setEntryTime(entry.getEntryTime());
        // 离场时间
        rep.setLeaveTime(entry.getLeaveTime());
        // 文件
        rep.setFileUrl(entry.getFilePath());
        // 是由
        rep.setReason(entry.getReason());

        return rep;
    }

    @Override
    public AppEntryApplicationRep queryEntryInfo(Integer id) {
        AppEntryApplicationRep ar = new AppEntryApplicationRep();
        //获取当前入场申请
        AppEntryApplication entry = appEntryApplicationService.selectByPrimaryKey(id);
        // 获取入场人员
        List<String> person = null;
        if(entry.getEntryPersonId().contains("/")){
            person = Arrays.asList(entry.getEntryPersonId().split("/"));
        }else {
            person =  Arrays.asList(entry.getEntryPersonId());
        }
        List<Integer> names = new ArrayList<>();
        List<QueryEmpSysIdDto> appEmpIds = sysUserService.getAppEmpEmpNamesIdList(person);
        for (QueryEmpSysIdDto emp : appEmpIds) {
            names.add(emp.getSysUserId());

        }
        // 入厂申请人员姓名
        ar.setEntryPersonName(names);

        // 获取组长
        List<String> leaders = Arrays.asList(String.valueOf(entry.getTeamLeaderId()));
        List<QueryEmpSysIdDto> empNamesIdList = sysUserService.getAppEmpEmpNamesIdList(leaders);
        for (QueryEmpSysIdDto emp : empNamesIdList) {
            ar.setTeamLeaderId(emp.getSysUserId());

        }
        ar.setEntryTime(entry.getEntryTime());
        ar.setLeaveTime(entry.getLeaveTime());
        // 分包
        ar.setSubcontractorId(entry.getSubcontractorId());

        // 总包
        ar.setGeneralContractorId(entry.getGeneralContractorId());

        // 监理
        ar.setSupervisionUnitId(entry.getSupervisionUnitId());

        // 业主
        ar.setOwnerUnit(entry.getOwnerUnit());

        // 审批
        ar.setApprovalStatus(entry.getApprovalStatus());

        // 上传文件
        ar.setFilePath(entry.getFilePath());

        // 申请事由
        ar.setReason(entry.getReason());
        return ar;
    }

    @Override
    public void edit(AppUpEntryApplicationDTO req) {
        appEntryApplicationService.edit(req);
    }

    /**
     * 获取下一节点类型（如分包的下一节点是总包）
     */
    private Integer getNextNode(Integer currentType) {
        switch (currentType) {
            case 4:
                return 3;
            case 3:
                return 2;
            case 2:
                return 1;
            case 1:
                return 0;
            default:
                return null;
        }
    }
}